﻿using System;
using System.Collections.Generic;
using System.Linq;
using ChiWalker.Utilities;
using Styx.WoWInternals;

namespace ChiWalker.Helpers
{
    public class Glyph
    {
        public static List<Glyph> SocketedGlyphs = new List<Glyph>();

        public Glyph(string name, GlyphType type, int socket, int glyphID)
        {
            Name = name;
            Type = type;
            Socket = socket;
            GlyphID = glyphID;
        }

        public string Name { get; set; }
        public GlyphType Type { get; set; }
        public int Socket { get; set; }
        public bool IsSocketed { get; set; }
        public int GlyphID { get; set; }

        private static List<string> GetGlyphSocketInfo(int index)
        {
            return Lua.GetReturnValues(String.Format("return GetGlyphSocketInfo({0})", index));
        }

        public static bool HasGlyph(string name)
        {
            return SocketedGlyphs.Count(g => g.Name == name) > 0;
        }

        public static bool HasGlyph(int glyphid)
        {
            return SocketedGlyphs.Count(g => g.GlyphID == glyphid) > 0;
        }

        public static void UpdateGlyphList()
        {
            SocketedGlyphs.Clear();
            var glyphCount = Lua.GetReturnVal<int>("return GetNumGlyphSockets()", 0);
            //Get Glyphs from sockets
            for (int i = 1; i <= glyphCount; i++)
            {
                List<string> socketInfo = GetGlyphSocketInfo(i);
                //If the count is less than 5 then the socket is empty
                if (socketInfo != null && socketInfo[0] != "nil" && socketInfo.Count >= 5)
                {
                    int id = int.Parse(socketInfo[5]);
                    int slot = i;
                    var type = (GlyphType) int.Parse(socketInfo[1]);
                    if (socketInfo[3] != "nil")
                    {
                        string name = WoWSpell.FromId(int.Parse(socketInfo[3])).Name.Replace("Glyph of ", "");
                        Logger.WriteVerbose("You have {0} in slot {1} of type {2} with id {3}", name, slot, type, id);
                        var newGlyph = new Glyph(name, type, slot, id);
                        SocketedGlyphs.Add(newGlyph);
                    }
                }
            }
        }
    }
}